package com.cq.hd.order.service.impl;

import com.cq.hd.common.enums.biz.OrderStateEnum;
import com.cq.hd.common.enums.biz.SubOrderStateEnum;
import com.cq.hd.common.response.Throw;
import com.cq.hd.order.mapper.TbOrderItemMapper;
import com.cq.hd.order.mapper.TbOrderMapper;
import com.cq.hd.order.param.OrderStateUpdateParam;
import com.cq.hd.order.po.TbOrderPo;
import com.cq.hd.order.service.OrderStateService;
import com.cq.hd.order.service.TbGroupBuyOrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.PlatformTransactionManager;

import javax.annotation.Resource;

/**
 * @author Much
 * @since 2024/09/22 13:00
 */
@Slf4j
@Service
public class OrderStateServiceImpl implements OrderStateService {

    @Resource
    private TbOrderMapper orderMapper;
    @Resource
    private TbOrderItemMapper orderItemMapper;
    @Resource
    private PlatformTransactionManager transactionManager;
    @Resource
    private TbGroupBuyOrderService groupBuyOrderService;

    @Override
    public int paid(OrderStateUpdateParam orderStateUpdateParam) {
        Long orderId = orderStateUpdateParam.getId();
        TbOrderPo tbOrderPo = orderMapper.selectById(orderId);
        if (OrderStateEnum.WAIT_VERIFY.getValue().equals(tbOrderPo.getOrderState())) {
            Throw.isBusinessException("订单" + orderId + "已是待核销状态");
        }
        orderStateUpdateParam.setOrderState(OrderStateEnum.WAIT_VERIFY.getValue());
        Integer res = orderMapper.updateOrderState(orderStateUpdateParam);
        if (res == 0) {
            log.error("更新订单" + tbOrderPo.getId() + "为待核销失败");
            Throw.isBusinessException("更新订单" + orderId + "为待核销失败");
        }

        // 如果活动需要审核，则状态为待审核状态，需要在商家后台审核
        Integer subOrderState = SubOrderStateEnum.WAIT_VERIFY.getValue();
        res = orderItemMapper.updateSubOrderStateByOrderId(orderId, subOrderState);
        if (res == 0) {
            log.error("更新子订单状态失败，orderId:{}", orderId);
            Throw.isBusinessException("更新子订单失败");
        }

        return 1;
    }

}
